package com.android.lib.messenger

import android.app.Application
import android.content.Intent
import android.os.Bundle
import com.android.lib.messenger.utils.Const
import com.android.lib.messenger.utils.ProcessUtils

object AndroidMessenger {

    private var context: Application? = null
    private var client: BinderClient? = null

    /**
     * 初始化框架,在主进程初始化
     */
    fun init(application: Application) {
        if (ProcessUtils.isMainProcess(application)) {
            context = application
            val intent = Intent(application, BinderServer::class.java)
            application.startService(intent)
        } else {
            client = BinderClient()
            client?.bindService(application)
        }
    }

    /**
     * 订阅消息
     *
     * @param key      消息唯一值
     * @param callback 消息回调
     */
    fun subscribe(key: String, callback: MessageCallback) {
        MessageProcessor.subscribe(key, callback)
    }

    /**
     * 取消订阅
     *
     * @param key 消息唯一值
     */
    fun unSubscribe(key: String) {
        MessageProcessor.unSubscribe(key)
    }

    /**
     * 发送消息
     *
     * @param key  接收消息唯一值
     * @param data data
     */
    fun post(key: String?, data: Bundle) {
        data.putString(Const.KEY_MESSAGE, key)
        if (null != client) {
            client?.sendMsg(data)
        } else {
            val intent = Intent(context, BinderServer::class.java)
            intent.putExtras(data)
            context?.startService(intent)
        }
    }


}